using System;
using System.Collections.Generic;
using System.Windows.Forms;
using WegasManagementSystem.BLL;
using WegasManagementSystem.Models;
using OfficeOpenXml;

namespace WegasManagementSystem.Forms
{
    public partial class SalaryItemForm : Form
    {
        private SalaryBLL _salaryBLL;
        private int? _editingItemId = null;

        public SalaryItemForm()
        {
            InitializeComponent();
            _salaryBLL = new SalaryBLL();
        }

        private void SalaryItemForm_Load(object sender, EventArgs e)
        {
            // 加载工资项目列表
            LoadSalaryItems();
            
            // 初始化类型下拉框
            InitializeTypeComboBox();
        }

        private void InitializeTypeComboBox()
        {
            // 初始化工资项目类型
            cboItemType.Items.Clear();
            cboItemType.Items.Add(new { Text = "收入项", Value = "income" });
            cboItemType.Items.Add(new { Text = "扣款项", Value = "deduction" });
            cboItemType.DisplayMember = "Text";
            cboItemType.ValueMember = "Value";
            cboItemType.SelectedIndex = 0;
        }

        private void LoadSalaryItems()
        {
            try
            {
                List<SalaryItem> salaryItems = _salaryBLL.GetAllSalaryItems();
                
                // 设置DataGridView数据源
                dgvSalaryItems.DataSource = salaryItems;
                
                // 设置列标题
                dgvSalaryItems.Columns["ItemId"].HeaderText = "项目ID";
                dgvSalaryItems.Columns["ItemName"].HeaderText = "项目名称";
                dgvSalaryItems.Columns["ItemType"].HeaderText = "项目类型";
                dgvSalaryItems.Columns["Formula"].HeaderText = "计算公式";
                dgvSalaryItems.Columns["Description"].HeaderText = "描述";
                dgvSalaryItems.Columns["IsActive"].HeaderText = "是否启用";
                dgvSalaryItems.Columns["CreatedTime"].HeaderText = "创建时间";
                dgvSalaryItems.Columns["UpdatedTime"].HeaderText = "更新时间";
                
                // 格式化项目类型显示
                dgvSalaryItems.Columns["ItemType"].DefaultCellStyle.Format = "income=收入项;deduction=扣款项";
                
                // 格式化是否启用显示
                dgvSalaryItems.Columns["IsActive"].DefaultCellStyle.Format = "1=是;0=否";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载工资项目列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            ClearInputs();
            _editingItemId = null;
            txtItemName.Focus();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(txtItemName.Text))
                {
                    MessageBox.Show("项目名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtItemName.Focus();
                    return;
                }

                // 创建工资项目对象
                SalaryItem salaryItem = new SalaryItem
                {
                    ItemName = txtItemName.Text.Trim(),
                    ItemType = cboItemType.SelectedItem != null ? (cboItemType.SelectedItem as dynamic).Value : "income",
                    Formula = txtFormula.Text.Trim(),
                    Description = txtDescription.Text.Trim(),
                    IsActive = chkIsActive.Checked ? 1 : 0
                };
                
                bool success = false;
                
                if (_editingItemId.HasValue)
                {
                    // 更新现有项目
                    salaryItem.ItemId = _editingItemId.Value;
                    success = _salaryBLL.UpdateSalaryItem(salaryItem);
                    if (success)
                    {
                        MessageBox.Show("工资项目更新成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    // 添加新项目
                    int newId = _salaryBLL.AddSalaryItem(salaryItem);
                    success = newId > 0;
                    if (success)
                    {
                        MessageBox.Show("工资项目添加成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                if (success)
                {
                    LoadSalaryItems();
                    ClearInputs();
                    _editingItemId = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存工资项目失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvSalaryItems.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择要删除的工资项目", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int itemId = Convert.ToInt32(dgvSalaryItems.SelectedRows[0].Cells["ItemId"].Value);
            string itemName = dgvSalaryItems.SelectedRows[0].Cells["ItemName"].Value.ToString();

            if (MessageBox.Show($"确定要删除工资项目\"{itemName}\"吗？\n删除后可能会影响工资计算结果！", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                try
                {
                    bool success = _salaryBLL.DeleteSalaryItem(itemId);
                    if (success)
                    {
                        MessageBox.Show("工资项目删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadSalaryItems();
                        ClearInputs();
                        _editingItemId = null;
                    }
                    else
                    {
                        MessageBox.Show("工资项目删除失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除工资项目失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void dgvSalaryItems_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvSalaryItems.SelectedRows.Count > 0)
            {
                try
                {
                    // 获取选中的项目ID
                    int itemId = Convert.ToInt32(dgvSalaryItems.SelectedRows[0].Cells["ItemId"].Value);
                    
                    // 获取项目详细信息
                    SalaryItem salaryItem = _salaryBLL.GetSalaryItemById(itemId);
                    
                    if (salaryItem != null)
                    {
                        // 在编辑面板显示项目信息
                        _editingItemId = salaryItem.ItemId;
                        txtItemName.Text = salaryItem.ItemName;
                        
                        // 设置项目类型
                        for (int i = 0; i < cboItemType.Items.Count; i++)
                        {
                            if ((cboItemType.Items[i] as dynamic).Value == salaryItem.ItemType)
                            {
                                cboItemType.SelectedIndex = i;
                                break;
                            }
                        }
                        
                        txtFormula.Text = salaryItem.Formula;
                        txtDescription.Text = salaryItem.Description;
                        chkIsActive.Checked = salaryItem.IsActive == 1;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载项目详情失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void ClearInputs()
        {
            txtItemName.Text = string.Empty;
            cboItemType.SelectedIndex = 0;
            txtFormula.Text = string.Empty;
            txtDescription.Text = string.Empty;
            chkIsActive.Checked = true;
        }
    }
} 